package com.threedt.nova.portfolio.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

@Repository(value = "genericDao")
public class GenericDaoImpl<T extends Serializable, ID extends Serializable>
		implements GenericDao<T, ID> {

	private EntityManager entityManager;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	@PersistenceContext(unitName = "NovaprotfolioPU")
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@SuppressWarnings("unchecked")
	public GenericDaoImpl() {

	}

	public T find(Class<T> cls, ID id) {
		return entityManager.find(cls, id);
	}

	public void persist(T entity) {
		entityManager.persist(entity);
	}

	public void merge(T entity) {
		entityManager.merge(entity);
	}

	public void remove(T entity) {
		entityManager.remove(entity);
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll(Class<T> cls) {
		return entityManager.createQuery(
				"Select t from " + cls.getSimpleName() + " t").getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<T> findInRange(Class<T> cls, int firstResult, int maxResults) {
		return entityManager.createQuery(
				"Select t from " + cls.getSimpleName() + " t").setFirstResult(
				firstResult).setMaxResults(maxResults).getResultList();
	}

	public long count(Class<T> cls) {
		return (Long) entityManager.createQuery(
				"Select count(t) from " + cls.getSimpleName() + " t")
				.getSingleResult();
	}

}
